package cz.muni.fi.pa165.dundd.serviceImpl;

import cz.muni.fi.pa165.dundd.assembler.Assembler;
import cz.muni.fi.pa165.dundd.dao.HeroDAO;
import cz.muni.fi.pa165.dundd.dao.HeroRoleDAO;
import cz.muni.fi.pa165.dundd.dto.HeroRoleDTO;
import cz.muni.fi.pa165.dundd.entity.Hero;
import cz.muni.fi.pa165.dundd.entity.HeroRole;
import cz.muni.fi.pa165.dundd.service.HeroRoleService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author xkonval
 */
@Service
@Transactional
public class HeroRoleServiceImpl implements HeroRoleService {

    @Autowired
    private HeroRoleDAO roleDAO;

    @Autowired
    private HeroDAO heroDAO;

    public void setHeroRoleDAO(HeroRoleDAO roleDAO) {
        this.roleDAO = roleDAO;
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void createRole(HeroRoleDTO roleDTO) {
        roleDAO.createRole(Assembler.heroRoleDtoToEntity(roleDTO));
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void updateRole(HeroRoleDTO roleDTO) {
        roleDAO.updateRole(Assembler.heroRoleDtoToEntity(roleDTO));
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public void deleteRole(HeroRoleDTO roleDTO) {
        HeroRole heroRole = Assembler.heroRoleDtoToEntity(roleDTO);
        for (Hero hero : heroDAO.retrieveAllHeroes()) {
            if ((hero.getRoles() != null) && hero.getRoles().contains(heroRole)) {
                hero.getRoles().remove(heroRole);
            }
        }
        roleDAO.deleteRole(heroRole);
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public HeroRoleDTO retrieveRoleById(Long id) {
        return Assembler.heroRoleEntityToDTO(roleDAO.retrieveRoleById(id));
    }

    @Override
    @Secured("IS_AUTHENTICATED_ANONYMOUSLY")
    public List<HeroRoleDTO> retrieveAllRoles() {
        List<HeroRole> retrieveAllRoles = roleDAO.retrieveAllRoles();
        List<HeroRoleDTO> result = new ArrayList<>();
        for (HeroRole h : retrieveAllRoles) {
            result.add(Assembler.heroRoleEntityToDTO(h));
        }
        return result;
    }
}
